package com.parleys.adapter;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.parleys.domain.PresentationAsset;
import com.parleys.helper.TimeUtil;

/**
 * Handles the layout of an element in the list of chapters.
 * 
 * @author David Van Droogenbroeck
 * 
 */
public class ChapterListAdapter extends BaseAdapter {

	private final List<PresentationAsset> data;
	private final Activity context;

	public ChapterListAdapter(final Activity context, final List<PresentationAsset> data) {
		this.context = context;
		this.data = data;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int location) {
		return data.get(location);
	}

	@Override
	public long getItemId(int id) {
		return id;
	}

	@Override
	public View getView(int position, View view, ViewGroup parent) {

		if (view == null) {
			LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			view = vi.inflate(android.R.layout.simple_list_item_1, null);
			ViewWrapper viewWrapper = new ViewWrapper(view);
			view.setTag(viewWrapper);
		}

		final PresentationAsset asset = data.get(position);
		if (asset != null) {
			final ViewWrapper viewWrapper = (ViewWrapper) view.getTag();

			String time = TimeUtil.getElapsedTimeMinutesSecondsString((int) (asset.getCuepoint() * 1000));
			StringBuilder titleBuilder = new StringBuilder(512);
			titleBuilder.append(asset.getSequence());
			titleBuilder.append(". ");
			titleBuilder.append(asset.getName());
			titleBuilder.append(" (");
			titleBuilder.append(time);
			titleBuilder.append(")");

			viewWrapper.getText1().setText(titleBuilder.toString());
			viewWrapper.getText1().setTextSize(18f);
		}

		return view;
	}

	private class ViewWrapper {
		private View view;
		private TextView text1;

		public ViewWrapper(View view) {
			super();
			this.view = view;
		}

		public TextView getText1() {
			if (text1 == null) {
				text1 = (TextView) view.findViewById(android.R.id.text1);
			}
			return text1;
		}
	}
}
